import 'package:e_book/components/book_content_tile/my_book_content_tile_skeleton.dart';
import 'package:e_book/model/book.dart';
import 'package:e_book/utils/toast_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:readmore/readmore.dart';
import 'package:url_launcher/url_launcher.dart';

class MyBookContentTitle extends StatelessWidget {
  final Book? book;
  final String? labelTitle;
  final List<String>? labels;
  const MyBookContentTitle(
      {super.key, this.labelTitle, this.labels, this.book});

  @override
  Widget build(BuildContext context) {
    if (book == null) {
      // 骨架屏
      return const MyBookContentTileSkeleton();
    } else {
      return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        // 标题
        Text(
          '内容简介',
          style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
        ),
        15.verticalSpace,
        // 内容
        ReadMoreText(
          book?.description ?? '',
          trimLines: 8, // 显示行数
          trimLength: 200, // 显示字数
          colorClickableText: Theme.of(context).colorScheme.primary,
          trimCollapsedText: '更多',
          trimExpandedText: '收起',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            height: 1.5, // 行高
          ),
        ),

        10.verticalSpace,

        // 更多信息
        Text(
          labelTitle ?? '',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.bold,
          ),
        ),

        10.verticalSpace,

        Wrap(
            children: List.generate(book!.buyInfo?.length ?? 0, (index) {
          return Padding(
            padding: EdgeInsets.only(right: 10.w),
            child: ActionChip(
              label: Text(
                '${book!.buyInfo?[index].name}: ￥${book!.buyInfo?[index].price}',
                style: TextStyle(fontSize: 12.sp),
              ),
              onPressed: () {
                _launchURL(book!.buyInfo?[index].url);
              },
            ),
          );
        }))
      ]);
    }
  }

  void _launchURL(String? url) async {
    if (url != null) {
      try {
        final Uri uri = Uri.parse(url);
        if (await canLaunchUrl(uri)) {
          await launchUrl(uri);
        } else {
          ToastUtils.showInfoMsg('无法打开链接');
          throw 'Could not launch $url';
        }
      } catch (e) {
        ToastUtils.showInfoMsg('无法打开链接');
      }
    }
  }
}
